package com.tanhua.app.interceptor;

import cn.hutool.core.util.StrUtil;
import com.tanhua.app.service.UserService;
import com.tanhua.domain.db.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class tokenInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;


    @Override  //在controller方法之前执行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 1 通过请求头Authorization获取token
        String token = request.getHeader("Authorization");
        // 2 判断app是否携带了token
        if(StrUtil.isEmpty(token)){
            response.setStatus(401); //权限不足
            return false;
        }
        //3 根据token获取redis中的User
        User user = userService.tokenfromUser(token);

        //4 判断token中是否有User
        if(user==null){
            response.setStatus(401);
            return false;
        }
        //5 将User存在我们的ThreadLocal
        UserHolder.saveUser(user);

        // 放行
        return true;
    }

    @Override  //controller结束要执行的
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        // 将User从threadlocal删除
        UserHolder.remove();
    }
}
